const Bpmn = require('bpmn-engine');
const EventEmitter = require('events').EventEmitter;

/*
const fs = require('fs');

let engine = new Bpmn.Engine({
    source: fs.readFileSync('./ass/1003.bpmn'),
    moddleOptions: {
        camunda: require('camunda-bpmn-moddle/resources/camunda')
    }
});
*/

/**
 input
 {
    engineName: xxx, // 流程名称
    engineSource: xxx, // 流程图
    state: xxx, // 流程保存的状态

    variables: { // 条件
        sum: 90,
        level: 60
    }

    nodeIds = []; // 节点IDs
 }

 output
 {
    activityIds[string] = [];
    curNodeIds[string] = [];
    state: any
 }

 */
let engine;
const activityIds = [];
const curNodeIds = [];
let callbackFun;
let errCs;

function setListener() {
    const listener = new EventEmitter();
    // 流程执行的线
    listener.on('taken', (flow) => {
        activityIds.push(flow.id);
    });
    return listener;
}
return function (data, callback) {
    callbackFun = callback;
    engine = new Bpmn.Engine({
        name: data.engineName,
        source: data.engineSource
    });
    engine.execute({
        variables: data.variables,
        listener: setListener()
    }, (err, definition) => {
        errCs = err;
    });
};

setTimeout(() => {
    // 返回到C#的代码
    callbackFun(errCs, {activityIds: activityIds, curNodeIds: curNodeIds, state: JSON.stringify(engine.getState())});
}, 30);